package com.robot.system.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.word.TableUtil;
import cn.hutool.poi.word.Word07Writer;
import com.robot.system.domain.entity.SysUser;
import gui.ava.html.Html2Image;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Font;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:TODO
 * @author:qzg
 * @Date:2020-12-24 16:20
 */
public class testServiceImpl {

    @SneakyThrows
    public static void main(String[] args) {
        /*HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        //imageGenerator.loadUrl("https://www.cnblogs.com/bnuvincent/p/6013425.html");
        imageGenerator.loadHtml("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>Title</title>\n" +
                "</head>\n" +
                "<style>\n" +
                "</style>\n" +
                "<body>\n" +
                "<table border=\"1\" cellspacing=\"0\">\n" +
                "    <tr >\n" +
                "        <td>测试转换图片</td>\n" +
                "        <td>甘特图什么鬼</td>\n" +
                "        <td>唉</td>\n" +
                "        <td>这难搞</td>\n" +
                "    </tr>\n" +
                "    <tr >\n" +
                "        <td>2020-12-1</td>\n" +
                "        <td>2020-12-2</td>\n" +
                "        <td>2020-12-3</td>\n" +
                "        <td>2020-12-4</td>\n" +
                "    </tr>\n" +
                "    <tr id=\"test\" style=\"background: #3a87ad\">\n" +
                "        <td>2021-1-1</td>\n" +
                "        <td>2021-1-2</td>\n" +
                "        <td>2021-1-3</td>\n" +
                "        <td>2021-1-4</td>\n" +
                "    </tr>\n" +
                "</table>\n" +
                "</body>\n" +
                "<script>\n" +
                "    document.getElementById(\"test\").style.cssText = \"background: #3a87ad\"\n" +
                "</script>\n" +
                "</html>");
        BufferedImage bufferedImage = new testServiceImpl().getGrayPicture(imageGenerator.getBufferedImage());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        /*try {
            ImageIO.write(bufferedImage,"png",FileUtil.file("d:/测试.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //imageGenerator.saveAsImage(FileUtil.file("d:/xx.png"));
        StringBuffer s = new StringBuffer();
        s.append("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>Title</title>\n" +
                "</head>\n" +
                "<style>\n" +
                "</style>\n" +
                "<body>\n" +
                "<h2>附表1：整体施工进度表</h2>\n" +
                "<table border=\"1\" cellspacing=\"0\" width=\"1000px\" style=\"height: 300px\">\n" +
                "    <tr >\n" +
                "        <td colspan=\"2\" style=\"text-align: center\" >年度</td>\n" +
                "        <td colspan=\"3\" style=\"text-align: center\">2019年</td>\n" +
                "        <td colspan=\"3\" style=\"text-align: center\">2020年</td>\n" +
                "    </tr>\n" +
                "    <tr >\n" +
                "        <td style=\"text-align: center\">主要工程项目</td>\n" +
                "        <td style=\"text-align: center\">月份</td>\n" +
                "        <td style=\"text-align: center\">10</td>\n" +
                "        <td style=\"text-align: center\">11</td>\n" +
                "        <td style=\"text-align: center\">12</td>\n" +
                "        <td style=\"text-align: center\">1</td>\n" +
                "        <td style=\"text-align: center\">2</td>\n" +
                "        <td style=\"text-align: center\">3</td>\n" +
                "    </tr>\n" +
                "    <tr >\n" +
                "        <td colspan=\"2\" style=\"text-align: center\">1.项目部驻地建设</td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 100px\">\n" +
                "            <div>\n" +
                "            <div style=\"background: #0c5460;align-content: center;height: 20%;width: 30%;position: absolute\"> &nbsp;</div>\n" +
                "            <div style=\"background: #985f0d;align-content: center;height: 20%;width: 70%;position: absolute;margin-left: 30%\"> &nbsp;</div>\n" +
                "        </div>\n" +
                "        </td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 100px\">\n" +
                "            <div style=\"background: #985f0d;align-content: center;height: 20%;width: 20%;position: absolute;margin-left: 0%\"> &nbsp;</div>\n" +
                "        </td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "    </tr>\n" +
                "    <tr >\n" +
                "        <td colspan=\"2\" style=\"text-align: center\">2.通信设备施工</td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 100px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #0c5460;align-content: center;height: 20%;width: 20%;position: absolute;margin-left: 80%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 100px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #0c5460;align-content: center;height: 20%;width: 80%;position: absolute\"> &nbsp;</div>\n" +
                "                <div style=\"background: #985f0d;align-content: center;height: 20%;width: 20%;position: absolute;margin-left: 80%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 100px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #985f0d;align-content: center;height: 20%;width: 40%;position: absolute;margin-left: 0%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "    </tr>\n" +
                "    <tr >\n" +
                "        <td colspan=\"2\" style=\"text-align: center\">3.收费系统施工</td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 50px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #0c5460;align-content: center;height: 20%;width: 20%;position: absolute;margin-left: 80%\"> &nbsp;</div>\n" +
                "                <div style=\"background: #985f0d;align-content: center;height: 20%;width: 0%;position: absolute;margin-left: 0%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 50px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #0c5460;align-content: center;height: 20%;width: 90%;position: absolute\"> &nbsp;</div>\n" +
                "                <div style=\"background: #985f0d;align-content: center;height: 20%;width: 10%;position: absolute;margin-left: 90%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 50px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #0c5460;align-content: center;height: 20%;width: 0%;position: absolute\"> &nbsp;</div>\n" +
                "                <div style=\"background: #985f0d;align-content: center;height: 20%;width: 10%;position: absolute;margin-left: 0%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "    </tr>\n" +
                "    <tr >\n" +
                "        <td colspan=\"2\" style=\"text-align: center\">4.监控系统施工</td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td width=\"100px\"></td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 50px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #0c5460;align-content: center;height: 20%;width: 50%;position: absolute\"> &nbsp;</div>\n" +
                "                <div style=\"background: #985f0d;align-content: center;height: 20%;width: 50%;position: absolute;margin-left: 50%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td style=\"position: relative;align-content: center;width: 50px\">\n" +
                "            <div>\n" +
                "                <div style=\"background: #0c5460;align-content: center;height: 20%;width: 0%;position: absolute\"> &nbsp;</div>\n" +
                "                <div style=\"background: #985f0d;align-content: center;height: 20%;width: 100%;position: absolute;margin-left: 0%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "    </tr>\n" +
                "    <!--<tr >\n" +
                "        <td style=\"position: relative;align-content: center\">\n" +
                "            <div>\n" +
                "            <div style=\"background: #0c5460;align-content: center;height: 20%;width: 50%;position: absolute\"> &nbsp;</div>\n" +
                "            <div style=\"background: #985f0d;align-content: center;height: 20%;width: 50%;position: absolute;margin-left: 50%\"> &nbsp;</div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "        <td>2020-12-2</td>\n" +
                "        <td>2020-12-3</td>\n" +
                "        <td>2020-12-4</td>\n" +
                "    </tr>-->\n" +
                "</table>\n" +
                "</body>\n" +
                "\n" +
                "<script>\n" +
                "</script>\n" +
                "</html>");
        Html2Image html2Image = Html2Image.fromHtml(String.valueOf(s));
        html2Image.getImageRenderer().saveImage(FileUtil.file("d:/xx.png"));
        Html2Image html2Image1 = new Html2Image();

        writer();
        ExcelReader reader = ExcelUtil.getReader("d:/test.xls");
        Integer num = reader.getSheetCount();
        System.out.println("共"+num+"张工作簿");
        if(num > 0){
            for(int i = 0;i<num;i++){
                List<List<Object>> readAll = reader.setSheet(i).read();
                System.out.println("工作簿："+ i+"："+reader.getSheet().getSheetName());
                if(readAll != null && readAll.size() >0){
                    for (int j = 0;j<readAll.size();j++){
                        System.out.println("第"+j+"行数据："+readAll.get(j));
                        if(j > 0){
                            String firstStr =  String.valueOf(readAll.get(j).get(0));
                            /*if(readAll.get(j).get(9).equals("√")) {
                                System.out.println("第一列数据：" + readAll.get(j).get(9));
                            }*/
                        }
                    }
                }
            }
        }
    }

    public BufferedImage getGrayPicture(BufferedImage originalImage)
    {
        BufferedImage grayPicture;
        int imageWidth = originalImage.getWidth();
        int imageHeight = originalImage.getHeight();

        grayPicture = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp cco = new ColorConvertOp(ColorSpace
                .getInstance(ColorSpace.CS_GRAY), null);
        cco.filter(originalImage, grayPicture);
        return grayPicture;
    }

    @SneakyThrows
    public static void createWordTable(){
        Word07Writer writer = new Word07Writer();
        XWPFTable xwpfTable = writer.getDoc().createTable(5,8);
        mergeCellsHorizontal(xwpfTable,0,0,7,8);
        List<Map> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("a","序号");
        map.put("b","分项工程名称");
        map.put("c","工期（天）");
        map.put("d","开始时间");
        map.put("f","完成时间");
        map.put("g","完成内容");
        map.put("h","需要条件");
        map.put("i","备注");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("j","___(XX项目)___ 机电工程施工进度计划表");
        TableUtil.writeRow(xwpfTable.getRow(0),map1,false);
        TableUtil.writeRow(xwpfTable.getRow(1),map,false);
        writerText(xwpfTable,2,4,list);

        //设置行高
        List<XWPFTableRow> xwpfTableRows = xwpfTable.getRows();
        for(XWPFTableRow xwpfTableRow : xwpfTableRows){
            CTTrPr trPr = xwpfTableRow.getCtRow().addNewTrPr();
            CTHeight ht = trPr.addNewTrHeight();
            ht.setVal(BigInteger.valueOf(500));
            //System.out.println(111111111);
        }

        //表格内容居中
        for(int i = 0 ;i < 5;i++){
            for(int j = 0;j<8;j++){
                System.out.println("位置："+i+","+j);
                XWPFTableCell cell = xwpfTable.getRow(i).getCell(j);
                /*CTTcPr tcPr = cell.getCTTc().addNewTcPr();
                CTVerticalJc jc = tcPr.addNewVAlign();
                jc.setVal(STVerticalJc.CENTER);*/
                CTTc cttc = cell.getCTTc();
                CTTcPr ctPr = cttc.addNewTcPr();
                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
            }
        }
        //TableUtil.createTable(writer.getDoc());
        //writer.getDoc().createTable(5,8);

        // 添加段落（标题）

// 写出到文件
        writer.flush(FileUtil.file("d:/wordWrite.docx"));
// 关闭
        writer.close();

        /*InputStream is = new FileInputStream("d:/wordWrite.docx");
        OutputStream os = new FileOutputStream("d:/wordWrite1.docx");
        XWPFDocument doc = new XWPFDocument(is);
        Range range = doc.getRange();
        range.replaceText("${name}","aaa");
        doc.write(os);
        is.close();
        os.flush();
        os.close();*/
    }

    /**
     * word跨列并单元格
     * @param table 表格对象
     * @param col 单元格所在行
     * @param fromRow 起始位置
     * @param toRow 结束位置
     */
    public static void mergeCellsHorizontal(XWPFTable table, int col, int fromRow, int toRow,int total) {
        for (int cellIndex = fromRow; cellIndex <= toRow; cellIndex++) {
            XWPFTableCell cell = table.getRow(col).getCell(cellIndex);
            if ( cellIndex == fromRow ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
        table.getRow(col).getCell(fromRow).getCTTc().addNewTcPr().addNewTcW()
                .setW(BigInteger.valueOf((9072 / total) * (toRow - fromRow + 1)));
    }


    /**
     * word跨行并单元格
     * @param table
     * @param col 单元格所在列
     * @param fromRow 起始行
     * @param toRow 结束行
     */
    public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            System.out.println(table.getRow(1).getCell(1).getCTTc().addNewTcPr().addNewVMerge());
            table.getRow(1).getCell(1).getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            if ( rowIndex == fromRow ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 写入数据
     */
    public static void writerText(XWPFTable table,int startNum,int endNum,List<Map> maps){
        Map<String,Object> map = new HashMap<>();
        map.put("num",1);
        map.put("poj","总则");
        maps.add(map);
        Map<String,Object> map1 = new HashMap<>();
        map1.put("num",2);
        map1.put("poj","项目部驻地建设");
        maps.add(map1);
        for (int i = startNum; i < maps.size()+startNum; i++){
            //for (int j = 0; j < maps.size();j++){
            System.out.println("第"+i+"行"+"\n"+maps.get(i-(maps.size())));
                TableUtil.writeRow(table.getRow(i),maps.get(i-(maps.size())),false);
            //}
        }
    }

    public static void writer(){
        Word07Writer writer = new Word07Writer();
        List<SysUser> list = new ArrayList<>();
        for(int i = 0;i<5;i++){
            SysUser sysUser = new SysUser();
            sysUser.setUserId(Long.valueOf(i+1));
            sysUser.setPassword(IdUtil.simpleUUID());
            sysUser.setAccount(IdUtil.randomUUID());
            sysUser.setRole(IdUtil.objectId());
            sysUser.setUserName(IdUtil.fastSimpleUUID());
            list.add(sysUser);
        }
        /*List<Map> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("a","子目编号");
        map.put("b","子目名称");
        map.put("c","单位");
        map.put("d","工程量");
        map.put("e","单价");
        map.put("f","合价");
        list.add(map);
        Map<String,Object> map1 = new HashMap<>();
        map1.put("a","900");
        map1.put("b","总则");
        map1.put("c","项");
        map1.put("d","20");
        map1.put("e","100000");
        map1.put("f","2000000");
        list.add(map1);*/
        System.out.println(list.toString());
        writer.addTable(list);

// 添加段落（标题）
        writer.addText(new Font("方正小标宋简体", Font.PLAIN, 22), "我是第一部分", "我是第二部分");
// 添加段落（正文）
        writer.addText(new Font("宋体", Font.PLAIN, 22), "我是正文第一部分", "我是正文第二部分");
// 写出到文件
        writer.flush(FileUtil.file("d:/wordWrite1.docx"));
// 关闭
        writer.close();
    }

    /**
     * 文本替换
     * @return
     */
    public XWPFDocument tranf(){
        XWPFDocument docx=null;
        try {
            docx=new XWPFDocument(new FileInputStream("d:/wordWrite1.docx"));

            //段落处理
            List<XWPFParagraph> paragraphs = docx.getParagraphs();                //07版需先获取段落；最后在获取以格式分割的最小单位run
            for (XWPFParagraph paragraph:paragraphs){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run:runs){
                    String str=run.getText(run.getTextPosition());         //获取run中的字符串
                    //System.out.println("1:"+str);
                   // for (Map.Entry<String,String> entry:replaceContent.entrySet()){   //循环替换
                      //str = str.replace(entry.getKey, entry.getValue);
                        str=str.replace("llll","测试替换");
                    //}
                    //System.out.println("2:"+str);
                    run.setText(str,0);
                }
            }

            //表格处理
            List<XWPFTable> xwpfTables = docx.getTables();
            for (XWPFTable xwpfTable : xwpfTables){
                List<XWPFTableRow> rows = xwpfTable.getRows();
                for (XWPFTableRow row : rows){
                    List<XWPFTableCell> xwpfTableCells = row.getTableCells();
                    for(XWPFTableCell cell : xwpfTableCells){
                        List<XWPFParagraph> xwpfParagraphs = cell.getParagraphs();
                        for(XWPFParagraph paragraph : xwpfParagraphs){
                            List<XWPFRun> runs = paragraph.getRuns();
                            for (XWPFRun run : runs) {
                                String str = run.getText(run.getTextPosition());
                                System.out.println("单元格值：" + str);
                                // for (Map.Entry<String,String> entry:replaceContent.entrySet()){   //循环替换
                                  //str = str.replace(entry.getKey, entry.getValue);
                                     str = str.replace("userId", "用户账户");
                                // }
                                run.setText(str,0);
                            }
                        }
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        Word07Writer writer = new Word07Writer(docx);
        writer.flush(FileUtil.file("d:/wordWrite2.docx"));
        return docx;
    }

}
